import Vue from "vue";
import Vuex from "vuex";

import app from "./modules/app";
import route from "./modules/route";
import snackbar from "./modules/snackbar"

import {LoginUser} from '@/api/user.js'

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    user: "",
    token: "",
    role: "",
  },
  mutations: {
    login(state, data) {
      state.user = data.user;
      state.token = data.token;
      state.role = data.user.roleId
      // 同时保存info到本地
      // console.log("Token in store: ", state.token)
      sessionStorage.setItem("token", JSON.stringify(state.token))
      // sessionStorage.setItem("user", JSON.stringify(state.user))
    },
    clear(state) {
      state.user = {}
      state.token = ""
    },
    updateUserInfo(state, user){
      state.user = user
    }
  },
  actions: {
    async AsyncLogin({commit}, info) {
      LoginUser(info).then(res => {
          commit("login", res.body);
      })            
    },
    PromiseLogin({commit}, info) {
      return new Promise((resolve, reject) => {
        LoginUser(info).then(res => {
          commit("login", res.body);
          resolve(res.body.user.roleId)
        })
        
      })
    }
  },
  getters: {
    token(state) {
      return state.token;
    },
    user(state) {
      return state.user;
    },
    role(state) {
      return state.role;
    },
  },
  modules: {
    app,
    route,
    snackbar,
  },
});
